package com.paradox.rpc.protocol.Netty;

import com.paradox.rpc.protocol.ParadoxClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettyClient implements ParadoxClient {

    private String inetHost;
    private Integer inetPort;

    private Channel channel;

    private NettyClientHandler handler=new NettyClientHandler();

    public NettyClient(String inetHost, Integer inetPort) {
        this.inetHost = inetHost;
        this.inetPort = inetPort;
    }

    public Channel start(){
        if(channel!=null){
            return channel;
        }

        Bootstrap bootstrap=new Bootstrap();
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup(1);
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline=socketChannel.pipeline();
                        pipeline.addLast("encoder",new ObjectEncoder());
                        pipeline.addLast("decoder",new ObjectDecoder(10240, ClassResolvers.cacheDisabled(null)));
                        pipeline.addLast(handler);
                    }
                });
        try {
            ChannelFuture future=bootstrap.connect(inetHost,inetPort).sync();
            channel=future.channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
            eventLoopGroup.shutdownGracefully();
        }
        return channel;
    }
}
